import 'dart:async';

import 'package:flutter/material.dart';

class CountDownButton extends StatefulWidget {
  const CountDownButton({
    required this.buttonText,
    required this.onTap,
    this.countDownSeconds = 30,
    super.key,
  });

  final String buttonText;
  final VoidCallback onTap;
  final int countDownSeconds;

  @override
  State<CountDownButton> createState() => _CountDownButtonState();
}

class _CountDownButtonState extends State<CountDownButton> {
  bool _isCountingDown = false;

  Timer? _timer;

  late int _countDownSeconds = widget.countDownSeconds;

  @override
  void dispose() {
    _timer?.cancel();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return TextButton(
      onPressed: _isCountingDown ? null : _onPressed,
      child: Text(_getButtonText()),
    );
  }

  void _onPressed() {
    _isCountingDown = true;

    if (mounted) {
      setState(() {});
    }

    Timer.periodic(const Duration(seconds: 1), (timer) {
      _timer ??= timer;
      _countDownSeconds--;

      if (mounted) {
        setState(() {});
      }

      if (_countDownSeconds == 0) {
        _timer!.cancel();
        _isCountingDown = false;
        _countDownSeconds = widget.countDownSeconds;

        if (mounted) {
          setState(() {});
        }
      }
    });

    widget.onTap();
  }

  String _getButtonText() {
    if (_isCountingDown) {
      return '${widget.buttonText} ($_countDownSeconds)';
    }

    return widget.buttonText;
  }
}
